package org.example.cdpcrpbackend.config.interceptor;

import cn.hutool.json.JSONUtil;
import org.example.cdpcrpbackend.controller.dto.Result;
import org.example.cdpcrpbackend.util.JwtTool;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 处理OPTIONS跨域请求
        if (request.getMethod().equalsIgnoreCase("OPTIONS")) {
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
            response.setHeader("Access-Control-Allow-Headers", "Authorization, Content-Type");
            response.setStatus(HttpServletResponse.SC_OK);
            return false; // 不继续处理其他请求
        }

        // 从 request 中获取 Authorization请求头
        String token = request.getHeader("Authorization");
        // 验证 token jwt
        if (JwtTool.verify(token)) {
            return true;
        } else {
            // 验证不通过，JSON 返回响应体
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            response.setContentType(MediaType.APPLICATION_JSON_VALUE);
            response.setCharacterEncoding("UTF-8");

            Result result = Result.fail("非法的 Token");
            String jsonResult = JSONUtil.toJsonStr(result);
            response.getWriter().write(jsonResult);
            return false;
        }
    }
}
